<!DOCTYPE html>
<html lang='en'><head>
  <title>图像分析与处理 | 江小凡的博客</title>
  <meta charset='utf-8'>
  <meta name="generator" content="Hugo 0.76.5" />
  <meta name = 'viewport' content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no'>
  <meta http-equiv = 'X-UA-Compatible' content = 'IE=edge'>
<meta property = 'og:locale' content = 'en_US' />
<meta property="og:type" content="article">
<meta property = 'og:title' content = '图像分析与处理' />
<meta name="description" content="Python 图像处理
写在前面
​    本篇文章主要对图像处理有基本认知,是项目开发中容易遇到的问题,并非处理ai人工智能识别与转换.(此外,目前市面上的图像识别以及语音识别已经发展的相当不错.大部分的ai都是根据github开源调试参数.)
​       多数图像处理与操作技术可以被两个库有效完成， …">
<meta property = 'og:description' content = 'Python 图像处理
写在前面
​    本篇文章主要对图像处理有基本认知,是项目开发中容易遇到的问题,并非处理ai人工智能识别与转换.(此外,目前市面上的图像识别以及语音识别已经发展的相当不错.大部分的ai都是根据github开源调试参数.)
​       多数图像处理与操作技术可以被两个库有效完成， …'>
<meta property = 'og:url' content = 'https://jxiaof.com/post/%E5%9B%BE%E5%83%8F%E5%88%86%E6%9E%90%E4%B8%8E%E5%A4%84%E7%90%86/' />
<meta property = 'og:image' content = 'https://jxiaof.com/images/pil.png'/>
<meta name = 'twitter:card' content = 'summary_large_image' />
<meta name = 'twitter:creator' content = ''>
<meta name = 'twitter:title' content = '图像分析与处理' />
<meta property = 'twitter:description'  content = 'Python 图像处理
写在前面
​    本篇文章主要对图像处理有基本认知,是项目开发中容易遇到的问题,并非处理ai人工智能识别与转换.(此外,目前市面上的图像识别以及语音识别已经发展的相当不错.大部分的ai都是根据github开源调试参数.)
​       多数图像处理与操作技术可以被两个库有效完成， …'/>
<meta name = 'twitter:image' content = 'https://jxiaof.com/images/pil.png' />
<link rel='apple-touch-icon' sizes='180x180' href='https://jxiaof.com/images/icons/apple-touch-icon.png'>
<link rel='icon' type='image/png' sizes='32x32' href='https://jxiaof.com/images/icons/favicon-32x32.png'>
<link rel='icon' type='image/png' sizes='16x16' href='https://jxiaof.com/images/icons/favicon-16x16.png'>
<link rel='manifest' href='https://jxiaof.com/images/icons/site.webmanifest'>

  <link rel='canonical' href='https://jxiaof.com/post/%E5%9B%BE%E5%83%8F%E5%88%86%E6%9E%90%E4%B8%8E%E5%A4%84%E7%90%86/'>
  <link rel = 'stylesheet' href = 'https://jxiaof.com/css/styles.b934c9412cc837b60543673c5f879b59569b1c7bea59b56896858a3b0a15220c8dbd91e80317b591a1857e31aa26b3bf8fbaca17c5bab12ff1231a272cd6bd6d.css' integrity = 'sha512-uTTJQSzIN7YFQ2c8X4ebWVabHHvqWbVoloWKOwoVIgyNvZHoAxe1kaGFfjGqJrO/j7rKF8W6sS/xIxonLNa9bQ=='>
</head>

  <body><div class = 'nav-drop'>
  <div class = 'nav-body'>
      <a href = 'https://jxiaof.com/about/' class = 'nav_item'>About</a>
    <div class = 'nav-close'></div>
  </div>
</div><header class = 'nav' >
  <nav class = 'nav-menu'>
    <a href='https://jxiaof.com/' class = 'nav-brand nav_item'>江小凡的博客</a>
    <div class = 'nav_bar-wrap'>
      <div class = 'nav_bar'></div>
    </div>
  </nav>
</header>


    <main>
<section class = 'post_header' style = 'background-image:url(https://jxiaof.com/images/pil.png);'>
  <h1 class='post_title'>图像分析与处理</h1>
</section>
<div class = 'post'>
  <article class='post_content'><p><strong>Python 图像处理</strong></p>
<p><strong>写在前面</strong></p>
<p>​    本篇文章主要对图像处理有基本认知,是项目开发中容易遇到的问题,并非处理ai人工智能识别与转换.(此外,目前市面上的图像识别以及语音识别已经发展的相当不错.大部分的ai都是根据github开源调试参数.)</p>
<p>​       多数图像处理与操作技术可以被两个库有效完成，它们是 <strong>Python Imaging Library (PIL)</strong> 与  <strong>OpenSource Computer Vision (OpenCV)</strong> 。</p>
<p>​     在项目开发过程中,极大概率会与前端对接时产生各种不一样的任务分配.后端开发程序员也必须对前端的图像图片有所了解.最起码能够尽快解决问题: 动态海报, 个性化推广码, 静态图片等.</p>
<h2 id="pillow">pillow</h2>
<p>pillow 是 一个活跃的PIL开发分支，可以运行所有的主流操作系统上，而且支持Python3。</p>
<p>首先我们了解几个概念: 色彩通道, 图片对象jpeg, png, gif等存储格式,一些基本的几何知识.</p>
<blockquote>
<p><code>mode</code> 属性定义了图像bands的数量和名称，以及像素类型和深度。常见的modes 有 “L” (luminance) <strong>表示灰度图像,</strong> “RGB” 表示<strong>真彩色图像</strong>, and “CMYK” 表示<strong>出版图像</strong>。</p>
</blockquote>
<p>​	PIL 模块支持大量图片格式。使用在 <code>Image</code> 模块的 <code>open()</code>函数从磁盘读取文件。你不需要知道文件格式就能打开它，这个库能够根据文件内容自动确定文件格式。</p>
<p>要保存文件，使用 <code>Image</code> 类的 <code>save()</code>方法。保存文件的时候文件名变得重要了。除非你指定格式，否则这个库将会以文件名的扩展名作为格式保存。</p>
<p>把方形图像做成圆形图像:这个场景很容易遇见,有很多中方式实现,比如几何切分,像素摘除等,至于方法效率,孰强孰弱,我只能说多学习几何.<strong>这时候就可以想一想如果要给每一个用户头像都加一个金环应该如何做?</strong></p>
<blockquote>
<p>生成一张图片是需要计算量的,同时,一个图片对象如果需要多次粘贴合并.可以通过将图片先划分图像区域处理,之后统一粘贴到一个透明底板.
值得注意的是: 输出png格式的图片会附带图片透明通道,保留更多细节,比如圆角处理.但不利于图片压缩.另外jpg图片是一种可以压缩的图片格式,可以极大的减少图片存储大小.可以根据不同业务,选择合适方案.</p>
</blockquote>
<h2 id="使用-image-类">使用 Image 类</h2>
<p>PIL最重要的类是 <a href="python/../reference/Image.html#PIL.Image.Image"><code>Image</code></a> class, 你可以通过多种方法创建这个类的实例；你可以从文件加载图像，或者处理其他图像, 或者从 scratch 创建。</p>
<p>要从文件加载图像，使用 <a href="python/../reference/Image.html#PIL.Image.open"><code>open()</code></a> 函数， 在 <a href="python/../reference/Image.html#module-PIL.Image"><code>Image</code></a> 模块:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">&gt;&gt;&gt;</span> <span style="color:#f92672">from</span> PIL <span style="color:#f92672">import</span> Image
<span style="color:#f92672">&gt;&gt;&gt;</span> im <span style="color:#f92672">=</span> Image<span style="color:#f92672">.</span>open(<span style="color:#e6db74">&#34;lena.ppm&#34;</span>)
  
</code></pre></div><p>加载成功将返回一个 <a href="python/../reference/Image.html#PIL.Image.Image"><code>Image</code></a> 对象。 你现在可以使用示例属性检查文件内容:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">&gt;&gt;&gt;</span> <span style="color:#f92672">from</span> __future__ <span style="color:#f92672">import</span> print_function
<span style="color:#f92672">&gt;&gt;&gt;</span> <span style="color:#66d9ef">print</span>(im<span style="color:#f92672">.</span>format, im<span style="color:#f92672">.</span>size, im<span style="color:#f92672">.</span>mode)
  PPM (<span style="color:#ae81ff">512</span>, <span style="color:#ae81ff">512</span>) RGB
  
</code></pre></div><p><code>format</code> 这个属性标识了图像来源。如果图像不是从文件读取它的值就是None。size属性是一个二元tuple，包含width和height（宽度和高度，单位都是px）。 <code>mode</code> 属性定义了图像bands的数量和名称，以及像素类型和深度。常见的modes 有 “L” (luminance) 表示灰度图像, “RGB” 表示真彩色图像, and “CMYK” 表示出版图像。</p>
<p>如果文件打开错误，返回 <code>IOError</code> 错误。</p>
<p>只要你有了 <a href="python/../reference/Image.html#PIL.Image.Image"><code>Image</code></a> 类的实例，你就可以通过类的方法处理图像。比如，下列方法可以显示图像:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">&gt;&gt;&gt;</span> im<span style="color:#f92672">.</span>show()
  
</code></pre></div><p>注解</p>
<p>标准的 <a href="python/../reference/Image.html#PIL.Image.Image.show"><code>show()</code></a> 效率并不高，它需要保存图像到临时文件然后通过 <strong>xv</strong> 显示图像。你需要先安装 <strong>xv</strong> ，显示图像有助于调试和测试。</p>
<p>下面的部分提供了这个库其他函数的概览。</p>
<h2 id="读写图像">读写图像</h2>
<p>PIL 模块支持大量图片格式。使用在 <a href="python/../reference/Image.html#module-PIL.Image"><code>Image</code></a> 模块的 <a href="python/../reference/Image.html#PIL.Image.open"><code>open()</code></a> 函数从磁盘读取文件。你不需要知道文件格式就能打开它，这个库能够根据文件内容自动确定文件格式。</p>
<p>要保存文件，使用 <a href="python/../reference/Image.html#PIL.Image.Image"><code>Image</code></a> 类的 <a href="python/../reference/Image.html#PIL.Image.Image.save"><code>save()</code></a> 方法。保存文件的时候文件名变得重要了。除非你指定格式，否则这个库将会以文件名的扩展名作为格式保存。</p>
<h3 id="转换文件格式到jpeg">转换文件格式到JPEG</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">from</span> __future__ <span style="color:#f92672">import</span> print_function
<span style="color:#f92672">import</span> os<span style="color:#f92672">,</span> sys
<span style="color:#f92672">from</span> PIL <span style="color:#f92672">import</span> Image

<span style="color:#66d9ef">for</span> infile <span style="color:#f92672">in</span> sys<span style="color:#f92672">.</span>argv[<span style="color:#ae81ff">1</span>:]:
  f, e <span style="color:#f92672">=</span> os<span style="color:#f92672">.</span>path<span style="color:#f92672">.</span>splitext(infile)
  outfile <span style="color:#f92672">=</span> f <span style="color:#f92672">+</span> <span style="color:#e6db74">&#34;.jpg&#34;</span>
  <span style="color:#66d9ef">if</span> infile <span style="color:#f92672">!=</span> outfile:
    <span style="color:#66d9ef">try</span>:
      Image<span style="color:#f92672">.</span>open(infile)<span style="color:#f92672">.</span>save(outfile)
      <span style="color:#66d9ef">except</span> <span style="color:#a6e22e">IOError</span>:
        <span style="color:#66d9ef">print</span>(<span style="color:#e6db74">&#34;cannot convert&#34;</span>, infile)
  
</code></pre></div><p><a href="python/../reference/Image.html#PIL.Image.Image.save"><code>save()</code></a> 方法的第二个参数可以指定文件格式，如果你使用非标准的扩展名你必须这样做：</p>
<h3 id="创建-jpeg-缩略图">创建 JPEG 缩略图</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">from</span> __future__ <span style="color:#f92672">import</span> print_function
<span style="color:#f92672">import</span> os<span style="color:#f92672">,</span> sys
<span style="color:#f92672">from</span> PIL <span style="color:#f92672">import</span> Image

size <span style="color:#f92672">=</span> (<span style="color:#ae81ff">128</span>, <span style="color:#ae81ff">128</span>)

<span style="color:#66d9ef">for</span> infile <span style="color:#f92672">in</span> sys<span style="color:#f92672">.</span>argv[<span style="color:#ae81ff">1</span>:]:
  outfile <span style="color:#f92672">=</span> os<span style="color:#f92672">.</span>path<span style="color:#f92672">.</span>splitext(infile)[<span style="color:#ae81ff">0</span>] <span style="color:#f92672">+</span> <span style="color:#e6db74">&#34;.thumbnail&#34;</span>
  <span style="color:#66d9ef">if</span> infile <span style="color:#f92672">!=</span> outfile:
    <span style="color:#66d9ef">try</span>:
      im <span style="color:#f92672">=</span> Image<span style="color:#f92672">.</span>open(infile)
      im<span style="color:#f92672">.</span>thumbnail(size)
      im<span style="color:#f92672">.</span>save(outfile, <span style="color:#e6db74">&#34;JPEG&#34;</span>)
      <span style="color:#66d9ef">except</span> <span style="color:#a6e22e">IOError</span>:
        <span style="color:#66d9ef">print</span>(<span style="color:#e6db74">&#34;cannot create thumbnail for&#34;</span>, infile)
  
</code></pre></div><p>很重要的一点是这个库不会直接解码或者加载图像栅格数据。当你打开一个文件，只会读取文件头信息用来确定格式，颜色模式，大小等等，文件的剩余部分不会主动处理。这意味着打开一个图像文件的操作十分快速，跟图片大小和压缩方式无关。下面是一个简单的脚本用来快速验证大量图片。</p>
<h3 id="验证图像文件">验证图像文件</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">from</span> __future__ <span style="color:#f92672">import</span> print_function
<span style="color:#f92672">import</span> sys
<span style="color:#f92672">from</span> PIL <span style="color:#f92672">import</span> Image

<span style="color:#66d9ef">for</span> infile <span style="color:#f92672">in</span> sys<span style="color:#f92672">.</span>argv[<span style="color:#ae81ff">1</span>:]:
  <span style="color:#66d9ef">try</span>:
    <span style="color:#66d9ef">with</span> Image<span style="color:#f92672">.</span>open(infile) <span style="color:#66d9ef">as</span> im:
      <span style="color:#66d9ef">print</span>(infile, im<span style="color:#f92672">.</span>format, <span style="color:#e6db74">&#34;</span><span style="color:#e6db74">%d</span><span style="color:#e6db74">x</span><span style="color:#e6db74">%d</span><span style="color:#e6db74">&#34;</span> <span style="color:#f92672">%</span> im<span style="color:#f92672">.</span>size, im<span style="color:#f92672">.</span>mode)
      <span style="color:#66d9ef">except</span> <span style="color:#a6e22e">IOError</span>:
        <span style="color:#66d9ef">pass</span>
  
</code></pre></div><h2 id="剪切粘贴合并图像">剪切，粘贴，合并图像</h2>
<p><a href="python/../reference/Image.html#PIL.Image.Image"><code>Image</code></a> 类包含的方法允许你操作图像部分选区。使用:py:meth:~PIL.Image.Image.crop 方法获取图像的一个子矩形选区。</p>
<h3 id="从图像中复制出一个矩形选区">从图像中复制出一个矩形选区</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python">box <span style="color:#f92672">=</span> (<span style="color:#ae81ff">100</span>, <span style="color:#ae81ff">100</span>, <span style="color:#ae81ff">400</span>, <span style="color:#ae81ff">400</span>)
region <span style="color:#f92672">=</span> im<span style="color:#f92672">.</span>crop(box)
  
</code></pre></div><p>矩形选区有一个4元元组定义，分别表示左、上、右、下的坐标。这个库以左上角为坐标原点，单位是px，所以上诉代码复制了一个 300x300 pixels 的矩形选区。这个选区现在可以被处理并且粘贴到原图。</p>
<h3 id="处理复制的矩形选区并粘贴到原图">处理复制的矩形选区并粘贴到原图</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python">region <span style="color:#f92672">=</span> region<span style="color:#f92672">.</span>transpose(Image<span style="color:#f92672">.</span>ROTATE_180)
im<span style="color:#f92672">.</span>paste(region, box)
  
</code></pre></div><p>当你粘贴矩形选区的时候必须保证尺寸一致。此外，矩形选区不能在图像外。然而你不必保证矩形选区和原图的颜色模式一致，因为矩形选区会被自动转换颜色（参看下面的 <a href="#color-transforms"><em>颜色变换</em></a> 部分），下面是一个例子：</p>
<h3 id="rolling-an-image">Rolling an image</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">roll</span>(image, delta):
      <span style="color:#e6db74">&#34;Roll an image sideways&#34;</span>
  
      xsize, ysize <span style="color:#f92672">=</span> image<span style="color:#f92672">.</span>size
  
      delta <span style="color:#f92672">=</span> delta <span style="color:#f92672">%</span> xsize
      <span style="color:#66d9ef">if</span> delta <span style="color:#f92672">==</span> <span style="color:#ae81ff">0</span>: <span style="color:#66d9ef">return</span> image
  
      part1 <span style="color:#f92672">=</span> image<span style="color:#f92672">.</span>crop((<span style="color:#ae81ff">0</span>, <span style="color:#ae81ff">0</span>, delta, ysize))
      part2 <span style="color:#f92672">=</span> image<span style="color:#f92672">.</span>crop((delta, <span style="color:#ae81ff">0</span>, xsize, ysize))
      image<span style="color:#f92672">.</span>paste(part2, (<span style="color:#ae81ff">0</span>, <span style="color:#ae81ff">0</span>, xsize<span style="color:#f92672">-</span>delta, ysize))
      image<span style="color:#f92672">.</span>paste(part1, (xsize<span style="color:#f92672">-</span>delta, <span style="color:#ae81ff">0</span>, xsize, ysize))
  
      <span style="color:#66d9ef">return</span> image
  
</code></pre></div><p>For more advanced tricks, the paste method can also take a transparency mask as an optional argument. In this mask, the value 255 indicates that the pasted image is opaque in that position (that is, the pasted image should be used as is). The value 0 means that the pasted image is completely transparent. Values in-between indicate different levels of transparency.</p>
<p>The Python Imaging Library also allows you to work with the individual bands of an multi-band image, such as an RGB image. The split method creates a set of new images, each containing one band from the original multi-band image. The merge function takes a mode and a tuple of images, and combines them into a new image. The following sample swaps the three bands of an RGB image:</p>
<h3 id="分离和合并颜色通道">分离和合并颜色通道</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python">r, g, b <span style="color:#f92672">=</span> im<span style="color:#f92672">.</span>split()
im <span style="color:#f92672">=</span> Image<span style="color:#f92672">.</span>merge(<span style="color:#e6db74">&#34;RGB&#34;</span>, (b, g, r))
  
</code></pre></div><p>Note that for a single-band image, <a href="python/../reference/Image.html#PIL.Image.Image.split"><code>split()</code></a> returns the image itself. To work with individual color bands, you may want to convert the image to “RGB” first.</p>
<h2 id="几何变换">几何变换</h2>
<p>The <a href="python/../reference/Image.html#PIL.Image.Image"><code>PIL.Image.Image</code></a> class contains methods to <a href="python/../reference/Image.html#PIL.Image.Image.resize"><code>resize()</code></a> and <a href="python/../reference/Image.html#PIL.Image.Image.rotate"><code>rotate()</code></a> an image. The former takes a tuple giving the new size, the latter the angle in degrees counter-clockwise.</p>
<h3 id="简单的几何变换">简单的几何变换</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python">out <span style="color:#f92672">=</span> im<span style="color:#f92672">.</span>resize((<span style="color:#ae81ff">128</span>, <span style="color:#ae81ff">128</span>))
  out <span style="color:#f92672">=</span> im<span style="color:#f92672">.</span>rotate(<span style="color:#ae81ff">45</span>) <span style="color:#75715e"># degrees counter-clockwise</span>
  
</code></pre></div><p>To rotate the image in 90 degree steps, you can either use the <a href="python/../reference/Image.html#PIL.Image.Image.rotate"><code>rotate()</code></a> method or the <a href="python/../reference/Image.html#PIL.Image.Image.transpose"><code>transpose()</code></a> method. The latter can also be used to flip an image around its horizontal or vertical axis.</p>
<h3 id="旋转图像">旋转图像</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python">out <span style="color:#f92672">=</span> im<span style="color:#f92672">.</span>transpose(Image<span style="color:#f92672">.</span>FLIP_LEFT_RIGHT)
  out <span style="color:#f92672">=</span> im<span style="color:#f92672">.</span>transpose(Image<span style="color:#f92672">.</span>FLIP_TOP_BOTTOM)
  out <span style="color:#f92672">=</span> im<span style="color:#f92672">.</span>transpose(Image<span style="color:#f92672">.</span>ROTATE_90)
  out <span style="color:#f92672">=</span> im<span style="color:#f92672">.</span>transpose(Image<span style="color:#f92672">.</span>ROTATE_180)
  out <span style="color:#f92672">=</span> im<span style="color:#f92672">.</span>transpose(Image<span style="color:#f92672">.</span>ROTATE_270)
  
</code></pre></div><p>There’s no difference in performance or result between <code>transpose(ROTATE)</code> and corresponding <a href="python/../reference/Image.html#PIL.Image.Image.rotate"><code>rotate()</code></a> operations.</p>
<p>A more general form of image transformations can be carried out via the <a href="python/../reference/Image.html#PIL.Image.Image.transform"><code>transform()</code></a> method.</p>
<h2 id="颜色变换">颜色变换</h2>
<p>The Python Imaging Library allows you to convert images between different pixel representations using the <a href="python/../reference/Image.html#PIL.Image.Image.convert"><code>convert()</code></a> method.</p>
<h3 id="颜色模式转换">颜色模式转换</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python">im <span style="color:#f92672">=</span> Image<span style="color:#f92672">.</span>open(<span style="color:#e6db74">&#34;lena.ppm&#34;</span>)<span style="color:#f92672">.</span>convert(<span style="color:#e6db74">&#34;L&#34;</span>)
  
</code></pre></div><p>The library supports transformations between each supported mode and the “L” and “RGB” modes. To convert between other modes, you may have to use an intermediate image (typically an “RGB” image).</p>
<h2 id="颜色增强">颜色增强</h2>
<p>The Python Imaging Library provides a number of methods and modules that can be used to enhance images.</p>
<h3 id="过滤器">过滤器</h3>
<p>The <a href="python/../reference/ImageFilter.html#module-PIL.ImageFilter"><code>ImageFilter</code></a> module contains a number of pre-defined enhancement filters that can be used with the <a href="python/../reference/Image.html#PIL.Image.Image.filter"><code>filter()</code></a> method.</p>
<h4 id="应用过滤器">应用过滤器</h4>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">from</span> PIL <span style="color:#f92672">import</span> ImageFilter
  out <span style="color:#f92672">=</span> im<span style="color:#f92672">.</span>filter(ImageFilter<span style="color:#f92672">.</span>DETAIL)
  
</code></pre></div><h3 id="点操作">点操作</h3>
<p>The <a href="python/../reference/Image.html#PIL.Image.Image.point"><code>point()</code></a> method can be used to translate the pixel values of an image (e.g. image contrast manipulation). In most cases, a function object expecting one argument can be passed to the this method. Each pixel is processed according to that function:</p>
<h4 id="应用点操作">应用点操作</h4>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#75715e"># multiply each pixel by 1.2</span>
  out <span style="color:#f92672">=</span> im<span style="color:#f92672">.</span>point(<span style="color:#66d9ef">lambda</span> i: i <span style="color:#f92672">*</span> <span style="color:#ae81ff">1.2</span>)
  
</code></pre></div><p>Using the above technique, you can quickly apply any simple expression to an image. You can also combine the <a href="python/../reference/Image.html#PIL.Image.Image.point"><code>point()</code></a> and <a href="python/../reference/Image.html#PIL.Image.Image.paste"><code>paste()</code></a> methods to selectively modify an image:</p>
<h4 id="处理个别bands">处理个别bands</h4>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#75715e"># split the image into individual bands</span>
  source <span style="color:#f92672">=</span> im<span style="color:#f92672">.</span>split()
  
  R, G, B <span style="color:#f92672">=</span> <span style="color:#ae81ff">0</span>, <span style="color:#ae81ff">1</span>, <span style="color:#ae81ff">2</span>
  
  <span style="color:#75715e"># select regions where red is less than 100</span>
  mask <span style="color:#f92672">=</span> source[R]<span style="color:#f92672">.</span>point(<span style="color:#66d9ef">lambda</span> i: i <span style="color:#f92672">&lt;</span> <span style="color:#ae81ff">100</span> <span style="color:#f92672">and</span> <span style="color:#ae81ff">255</span>)
  
  <span style="color:#75715e"># process the green band</span>
  out <span style="color:#f92672">=</span> source[G]<span style="color:#f92672">.</span>point(<span style="color:#66d9ef">lambda</span> i: i <span style="color:#f92672">*</span> <span style="color:#ae81ff">0.7</span>)
  
  <span style="color:#75715e"># paste the processed band back, but only where red was &lt; 100</span>
  source[G]<span style="color:#f92672">.</span>paste(out, None, mask)
  
  <span style="color:#75715e"># build a new multiband image</span>
  im <span style="color:#f92672">=</span> Image<span style="color:#f92672">.</span>merge(im<span style="color:#f92672">.</span>mode, source)
  
</code></pre></div><p>Note the syntax used to create the mask:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python">imout <span style="color:#f92672">=</span> im<span style="color:#f92672">.</span>point(<span style="color:#66d9ef">lambda</span> i: expression <span style="color:#f92672">and</span> <span style="color:#ae81ff">255</span>)
  
</code></pre></div><p>Python only evaluates the portion of a logical expression as is necessary to determine the outcome, and returns the last value examined as the result of the expression. So if the expression above is false (0), Python does not look at the second operand, and thus returns 0. Otherwise, it returns 255.</p>
<h3 id="增强">增强</h3>
<p>For more advanced image enhancement, you can use the classes in the <a href="python/../reference/ImageEnhance.html#module-PIL.ImageEnhance"><code>ImageEnhance</code></a> module. Once created from an image, an enhancement object can be used to quickly try out different settings.</p>
<p>You can adjust contrast, brightness, color balance and sharpness in this way.</p>
<h4 id="增强图形">增强图形</h4>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">from</span> PIL <span style="color:#f92672">import</span> ImageEnhance
  
  enh <span style="color:#f92672">=</span> ImageEnhance<span style="color:#f92672">.</span>Contrast(im)
  enh<span style="color:#f92672">.</span>enhance(<span style="color:#ae81ff">1.3</span>)<span style="color:#f92672">.</span>show(<span style="color:#e6db74">&#34;30% more contrast&#34;</span>)
  
</code></pre></div><h2 id="多帧图像序列">多帧图像序列</h2>
<p>The Python Imaging Library contains some basic support for image sequences (also called animation formats). Supported sequence formats include FLI/FLC, GIF, and a few experimental formats. TIFF files can also contain more than one frame.</p>
<p>When you open a sequence file, PIL automatically loads the first frame in the sequence. You can use the seek and tell methods to move between different frames:</p>
<h3 id="读取序列">读取序列</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">from</span> PIL <span style="color:#f92672">import</span> Image
  
  im <span style="color:#f92672">=</span> Image<span style="color:#f92672">.</span>open(<span style="color:#e6db74">&#34;animation.gif&#34;</span>)
  im<span style="color:#f92672">.</span>seek(<span style="color:#ae81ff">1</span>) <span style="color:#75715e"># skip to the second frame</span>
  
  <span style="color:#66d9ef">try</span>:
      <span style="color:#66d9ef">while</span> <span style="color:#ae81ff">1</span>:
          im<span style="color:#f92672">.</span>seek(im<span style="color:#f92672">.</span>tell()<span style="color:#f92672">+</span><span style="color:#ae81ff">1</span>)
          <span style="color:#75715e"># do something to im</span>
  <span style="color:#66d9ef">except</span> <span style="color:#a6e22e">EOFError</span>:
      <span style="color:#66d9ef">pass</span> <span style="color:#75715e"># end of sequence</span>
  
</code></pre></div><p>As seen in this example, you’ll get an <code>EOFError</code> exception when the sequence ends.</p>
<p>Note that most drivers in the current version of the library only allow you to seek to the next frame (as in the above example). To rewind the file, you may have to reopen it.</p>
<p>The following iterator class lets you to use the for-statement to loop over the sequence:</p>
<h3 id="序列迭代-class">序列迭代 class</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-fallback" data-lang="fallback">class ImageSequence:
      def __init__(self, im):
          self.im = im
      def __getitem__(self, ix):
          try:
              if ix:
                  self.im.seek(ix)
              return self.im
          except EOFError:
              raise IndexError # end of sequence
  
  for frame in ImageSequence(im):
      # ...do something to frame...
</code></pre></div><h2 id="postscript-打印">Postscript 打印</h2>
<p>The Python Imaging Library includes functions to print images, text and graphics on Postscript printers. Here’s a simple example:</p>
<h3 id="drawing-postscript">Drawing Postscript</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">from</span> PIL <span style="color:#f92672">import</span> Image
  <span style="color:#f92672">from</span> PIL <span style="color:#f92672">import</span> PSDraw
  
  im <span style="color:#f92672">=</span> Image<span style="color:#f92672">.</span>open(<span style="color:#e6db74">&#34;lena.ppm&#34;</span>)
  title <span style="color:#f92672">=</span> <span style="color:#e6db74">&#34;lena&#34;</span>
  box <span style="color:#f92672">=</span> (<span style="color:#ae81ff">1</span><span style="color:#f92672">*</span><span style="color:#ae81ff">72</span>, <span style="color:#ae81ff">2</span><span style="color:#f92672">*</span><span style="color:#ae81ff">72</span>, <span style="color:#ae81ff">7</span><span style="color:#f92672">*</span><span style="color:#ae81ff">72</span>, <span style="color:#ae81ff">10</span><span style="color:#f92672">*</span><span style="color:#ae81ff">72</span>) <span style="color:#75715e"># in points</span>
  
  ps <span style="color:#f92672">=</span> PSDraw<span style="color:#f92672">.</span>PSDraw() <span style="color:#75715e"># default is sys.stdout</span>
  ps<span style="color:#f92672">.</span>begin_document(title)
  
  <span style="color:#75715e"># draw the image (75 dpi)</span>
  ps<span style="color:#f92672">.</span>image(box, im, <span style="color:#ae81ff">75</span>)
  ps<span style="color:#f92672">.</span>rectangle(box)
  
  <span style="color:#75715e"># draw centered title</span>
  ps<span style="color:#f92672">.</span>setfont(<span style="color:#e6db74">&#34;HelveticaNarrow-Bold&#34;</span>, <span style="color:#ae81ff">36</span>)
  w, h, b <span style="color:#f92672">=</span> ps<span style="color:#f92672">.</span>textsize(title)
  ps<span style="color:#f92672">.</span>text((<span style="color:#ae81ff">4</span><span style="color:#f92672">*</span><span style="color:#ae81ff">72</span><span style="color:#f92672">-</span>w<span style="color:#f92672">/</span><span style="color:#ae81ff">2</span>, <span style="color:#ae81ff">1</span><span style="color:#f92672">*</span><span style="color:#ae81ff">72</span><span style="color:#f92672">-</span>h), title)
  
  ps<span style="color:#f92672">.</span>end_document()
  
</code></pre></div><h2 id="更多关于读取图像">更多关于读取图像</h2>
<p>As described earlier, the <a href="python/../reference/Image.html#PIL.Image.open"><code>open()</code></a> function of the <a href="python/../reference/Image.html#module-PIL.Image"><code>Image</code></a> module is used to open an image file. In most cases, you simply pass it the filename as an argument:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python">im <span style="color:#f92672">=</span> Image<span style="color:#f92672">.</span>open(<span style="color:#e6db74">&#34;lena.ppm&#34;</span>)
  
</code></pre></div><p>If everything goes well, the result is an <a href="python/../reference/Image.html#PIL.Image.Image"><code>PIL.Image.Image</code></a> object. Otherwise, an <code>IOError</code> exception is raised.</p>
<p>You can use a file-like object instead of the filename. The object must implement <a href="http://docs.python.org/2/library/stdtypes.html#file.read"><code>read()</code></a>, <a href="http://docs.python.org/2/library/stdtypes.html#file.seek"><code>seek()</code></a> and <a href="http://docs.python.org/2/library/stdtypes.html#file.tell"><code>tell()</code></a> methods, and be opened in binary mode.</p>
<h3 id="从文件读取">从文件读取</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python">fp <span style="color:#f92672">=</span> open(<span style="color:#e6db74">&#34;lena.ppm&#34;</span>, <span style="color:#e6db74">&#34;rb&#34;</span>)
im <span style="color:#f92672">=</span> Image<span style="color:#f92672">.</span>open(fp)
  
</code></pre></div><p>To read an image from string data, use the <a href="http://docs.python.org/2/library/stringio.html#StringIO.StringIO"><code>StringIO</code></a> class:</p>
<h3 id="从-string-读取">从 string 读取</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">import</span> StringIO
im <span style="color:#f92672">=</span> Image<span style="color:#f92672">.</span>open(StringIO<span style="color:#f92672">.</span>StringIO(buffer))
  
</code></pre></div><p>Note that the library rewinds the file (using <code>seek(0)</code>) before reading the image header. In addition, seek will also be used when the image data is read (by the load method). If the image file is embedded in a larger file, such as a tar file, you can use the <a href="python/../PIL.html#module-PIL.ContainerIO"><code>ContainerIO</code></a> or <a href="python/../PIL.html#module-PIL.TarIO"><code>TarIO</code></a> modules to access it.</p>
<h3 id="从压缩包读取">从压缩包读取</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">from</span> PIL <span style="color:#f92672">import</span> TarIO

fp <span style="color:#f92672">=</span> TarIO<span style="color:#f92672">.</span>TarIO(<span style="color:#e6db74">&#34;Imaging.tar&#34;</span>, <span style="color:#e6db74">&#34;Imaging/test/lena.ppm&#34;</span>)
im <span style="color:#f92672">=</span> Image<span style="color:#f92672">.</span>open(fp)

</code></pre></div><h2 id="控制解码器">控制解码器</h2>
<p>Some decoders allow you to manipulate the image while reading it from a file. This can often be used to speed up decoding when creating thumbnails (when speed is usually more important than quality) and printing to a monochrome laser printer (when only a greyscale version of the image is needed).</p>
<p>The <a href="python/../reference/Image.html#PIL.Image.Image.draft"><code>draft()</code></a> method manipulates an opened but not yet loaded image so it as closely as possible matches the given mode and size. This is done by reconfiguring the image decoder.</p>
<h3 id="reading-in-draft-mode">Reading in draft mode</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">from</span> __future__ <span style="color:#f92672">import</span> print_function
im <span style="color:#f92672">=</span> Image<span style="color:#f92672">.</span>open(file)
<span style="color:#66d9ef">print</span>(<span style="color:#e6db74">&#34;original =&#34;</span>, im<span style="color:#f92672">.</span>mode, im<span style="color:#f92672">.</span>size)

im<span style="color:#f92672">.</span>draft(<span style="color:#e6db74">&#34;L&#34;</span>, (<span style="color:#ae81ff">100</span>, <span style="color:#ae81ff">100</span>))
<span style="color:#66d9ef">print</span>(<span style="color:#e6db74">&#34;draft =&#34;</span>, im<span style="color:#f92672">.</span>mode, im<span style="color:#f92672">.</span>size)
  
</code></pre></div><p>This prints something like:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python">original <span style="color:#f92672">=</span> RGB (<span style="color:#ae81ff">512</span>, <span style="color:#ae81ff">512</span>)
draft <span style="color:#f92672">=</span> L (<span style="color:#ae81ff">128</span>, <span style="color:#ae81ff">128</span>)
  
</code></pre></div><p>Note that the resulting image may not exactly match the requested mode and size. To make sure that the image is not larger than the given size, use the thumbnail method instead.</p>
<hr>
    <div class = 'post_extra'><div class = 'copy' data-share = 'Share Story' data-copied = 'Link Copied'>
  <svg>
    <use xlink:href="#copy"></use>
  </svg>  
</div>

    </div>

  </article>
  <div class="post-comment">
       
       <h3>Comments welcome !</h3>



<div id="vcomments"></div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src='//unpkg.com/valine/dist/Valine.min.js'></script>
 <script type="text/javascript">
   new Valine({
       el: '#vcomments' ,
       appId: 'xb5Xl8O60fXEK4d13KsazkkL-gzGzoHsz',
       appKey: 'qyztiJ2tgf6AhvsrH088N29o',
       notify: 'false', 
       verify: 'false', 
       avatar:'mm', 
       placeholder: '说说你的看法吧...',
       visitor: 'true'
   });
 </script>
  </div>
  <aside><h3></h3>
<ul class='posts aside'>
<li class = 'post_item'>
  <a class = 'post_card' href='https://jxiaof.com/post/first/' title = 'ABOUT MYSELF' style = 'background-image: url(https://jxiaof.com/images/speakers.jpg);'>
  </a>
  <div class = 'excerpt'>
    <div class = 'excerpt_meta'><div class = 'copy' data-share = 'Share Story' data-copied = 'Link Copied'>
  <svg>
    <use xlink:href="#copy"></use>
  </svg>  
</div>

    </div>
    <h3 class = 'post_link'>
      <a href='https://jxiaof.com/post/first/'>ABOUT MYSELF</a>
    </h3>
    <p class = 'pale'><p>​        I am a light game enthusiast with poor gastrointestinal function. I go to bed …</p></p>
  </div>
</li>

<li class = 'post_item'>
  <a class = 'post_card' href='https://jxiaof.com/post/leetcode/' title = 'Leetcode' style = 'background-image: url(https://jxiaof.com/images/programmer.png);'>
  </a>
  <div class = 'excerpt'>
    <div class = 'excerpt_meta'><div class = 'copy' data-share = 'Share Story' data-copied = 'Link Copied'>
  <svg>
    <use xlink:href="#copy"></use>
  </svg>  
</div>

    </div>
    <h3 class = 'post_link'>
      <a href='https://jxiaof.com/post/leetcode/'>Leetcode</a>
    </h3>
    <p class = 'pale'>买卖股票简答:
class Solution: def maxProfit(self, prices): &#34;&#34;&#34; :type prices: …</p>
  </div>
</li>

</ul>

  </aside>
</div>
<script src = 'https://jxiaof.com/js/autosize.min.js'></script>
<script src = 'https://jxiaof.com/js/timeago.js'></script>
    </main><svg width="0" height="0" class="hidden">
  <symbol viewBox="0 0 699.428 699.428" xmlns="http://www.w3.org/2000/svg" id="copy">
    <path d="M502.714 0H240.428C194.178 0 153 42.425 153 87.429l-25.267.59c-46.228 0-84.019 41.834-84.019 86.838V612c0 45.004 41.179 87.428 87.429 87.428H459c46.249 0 87.428-42.424 87.428-87.428h21.857c46.25 0 87.429-42.424 87.429-87.428v-349.19zM459 655.715H131.143c-22.95 0-43.714-21.441-43.714-43.715V174.857c0-22.272 18.688-42.993 41.638-42.993l23.933-.721v393.429C153 569.576 194.178 612 240.428 612h262.286c0 22.273-20.765 43.715-43.714 43.715zm153-131.143c0 22.271-20.765 43.713-43.715 43.713H240.428c-22.95 0-43.714-21.441-43.714-43.713V87.429c0-22.272 20.764-43.714 43.714-43.714H459c-.351 50.337 0 87.975 0 87.975 0 45.419 40.872 86.882 87.428 86.882H612zm-65.572-349.715c-23.277 0-43.714-42.293-43.714-64.981V44.348L612 174.857zm-43.714 131.537H306c-12.065 0-21.857 9.77-21.857 21.835s9.792 21.835 21.857 21.835h196.714c12.065 0 21.857-9.771 21.857-21.835 0-12.065-9.792-21.835-21.857-21.835zm0 109.176H306c-12.065 0-21.857 9.77-21.857 21.834 0 12.066 9.792 21.836 21.857 21.836h196.714c12.065 0 21.857-9.77 21.857-21.836 0-12.064-9.792-21.834-21.857-21.834z"
    ></path>
  </symbol>
  <symbol viewBox="0 0 60.015 60.015" xmlns="http://www.w3.org/2000/svg" id="reply">
    <path d="M42.007 0h-24c-9.925 0-18 8.075-18 18v14c0 9.59 7.538 17.452 17 17.973v8.344a1.694 1.694 0 0 0 1.699 1.698c.44 0 .873-.173 1.198-.498l1.876-1.876C26.708 52.713 33.259 50 40.227 50h1.78c9.925 0 18-8.075 18-18V18c0-9.925-8.075-18-18-18zm16 32c0 8.822-7.178 16-16 16h-1.78c-7.502 0-14.556 2.921-19.86 8.226l-1.359 1.359V44a1 1 0 1 0-2 0v3.949c-8.356-.52-15-7.465-15-15.949V18c0-8.822 7.178-16 16-16h24c8.822 0 16 7.178 16 16v14z"></path>
  </symbol>
</svg>
<footer class = 'footer'>
  <div class = 'footer_inner wrap pale'>
    <p>&copy;&nbsp;<span class = 'year'></span>&nbsp;江小凡的博客.
    Designed by  <a href = 'https://www.github.com/jxiaof' title = 'Linkedin Profile'>江小凡</a></p>
  </div>
</footer>
<script src = 'https://jxiaof.com/js/index.min.c3b0a769e56310d4359f30762ab615db8cd6ce33d555ee7f68d25e8a40c63ce18bf6b273d35a9b5c033a7f6e71b1d424e74d9f542d93482215c671b3f31f885f.js'></script>

  </body>
</html>
